<?php
/**
 * Created by PhpStorm.
 * User: 64423
 * Date: 2018/10/24
 * Time: 10:13
 */

namespace app\api\exception;


use Exception;
use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandle extends Handle
{
    private $code;
    private $msg;
    private $error_code;

    public function render(Exception $e)
    {
        if($e instanceof BaseException){
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->error_code = $e->error_code;
        }else{
            // 开发模式下不记录错误日志，使用自带异常处理类
            if(config('app_debug')){
                return parent::render($e);
            }else{
                // 生产环境记录日志，返回json格式错误
                $this->code = 500;
                $this->msg = '程序猿走丢了';
                $this->error_code = '999';
                $this->recordErrorLog($e);
            }
        }
        $request = Request::instance();
        $result =  [
            'msg' => $this->msg,
            'error_code' => $this->error_code,
            'request_url' => $request->url()
        ];
        return json($result, $this->code);
    }

    private function recordErrorLog(Exception $e)
    {
        Log::init([
            'type' => 'File',
            'path' => LOG_PATH,
            'level' => ['error']
        ]);
        Log::record($e->getMessage(), 'error');
    }
}